const Comment = require('../models/comment');
const Notification = require('../models/notification');
const Post = require('../models/post');
const { validationResult } = require('express-validator');

const commentController = {
    async create(req, res, next) {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { content } = req.body;

        try {
            const post = await Post.findById(req.params.post_id);
            if (!post) {
                return res.status(404).json({ error: 'Post not found' });
            }

            const { comment_id } = await Comment.create({
                post_id: req.params.post_id,
                user_id: req.user.user_id,
                content
            });

            if (post.user_id !== req.user.user_id) {
                await Notification.create({
                    user_id: post.user_id,
                    type: 'comment',
                    related_user_id: req.user.user_id,
                    related_post_id: req.params.post_id,
                    content: `${req.user.user_id} commented on your post`
                });
            }

            res.status(201).json({ comment_id });
        } catch (error) {
            next(error);
        }
    },

    async getByPostId(req, res, next) {
        const { limit = 10, offset = 0 } = req.query;

        try {
            const comments = await Comment.findByPostId(req.params.post_id, parseInt(limit), parseInt(offset));
            res.json(comments);
        } catch (error) {
            next(error);
        }
    }
};

module.exports = commentController;